package com.bckj.fastboot.paid.biz.domain.pay.service;

import com.bckj.fastboot.core.execution.ExecutionProvider;
import com.bckj.fastboot.paid.api.constant.PayExecutionNames;
import com.bckj.fastboot.paid.api.entity.PayOrder;
import com.bckj.fastboot.paid.api.model.PayResult;
import com.bckj.fastboot.paid.biz.domain.pay.context.PayContext;
import com.bckj.fastboot.paid.biz.domain.pay.repo.PayOrderRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class PayOrderDomainService {

    private final PayOrderRepository payOrderRepository;

    public void pay(PayContext ctx) {
        ExecutionProvider.get(PayExecutionNames.PAY_ORDER_CREATE).execute(ctx);
    }

    /**
     * 处理支付订单结果
     */
    public void setPayResult(PayResult payResult) {
        PayOrder payOrder = payOrderRepository.lambdaQuery().eq(PayOrder::getOutTradeNo, payResult.getOutTradeNo()).one();
        payOrderRepository.lambdaUpdate()
                .eq(PayOrder::getId, payOrder.getId())
                .set(PayOrder::getStatus, payResult.getStatus())
                .update();
        fillPayResult(payResult, payOrder);
    }

    private void fillPayResult(PayResult payResult, PayOrder payOrder) {
        payResult.setTrxNo(payOrder.getTrxNo());
        payResult.setPayWay(payOrder.getPayWay());
        payResult.setAmount(payOrder.getAmount());
    }
}
